<script setup>
import { reactive, ref } from "vue";
import { Edit, Delete, Search, RefreshRight, UserFilled } from "@element-plus/icons-vue";
import { findUserPageList, updateUser, deleteUser, selectById } from "@/api/admin/user.js";
import { showMessage, showModel } from "@/composables/util.js";
import { uploadFile } from "@/api/common/file"
import moment from 'moment'
// 定义响应式的表单对象
const form = reactive({
  username: '',
  startDate: '',
  endDate: '',
  role: 'BLOGGER'
})
// 控制个人信息弹出框
let info = ref(false)
const updateForm = reactive({
  id: null,
  username: null,
  password: '',
  avatar: null,
})

const handleAvatarChange = (file) => {
    // 创建表单对象
    let formData = new FormData()
    formData.append('file', file.raw)
    // 调用后台文件上传接口
    uploadFile(formData).then((e) => {
        // 响参失败，提示错误消息
        if (e.data.success == false) {
            let message = e.message
            showMessage(message, 'error')
            return
        }
        // 成功则设置头像链接，并提示成功
        updateForm.avatar = e.data.data
        console.log("头像地址：" + updateForm.avatar)
    })
}

const selectOneUser = (id) => {
  info.value = true
  selectById({id: id}).then((res) => {
    if (res.data.success === true) {
      console.log(res.data.data)
      updateForm.id = res.data.data.id
      updateForm.username = res.data.data.username
      updateForm.avatar = res.data.data.avatar
    } else {
      let message = res.data.message
      console.log(message)
      // 提示消息
      showMessage(message, 'error')
    }
  })
}
// 修改用户信息
const saveInfo = () => {
    // 调用后端修改用户信息接口
    updateUser(updateForm).then((res) => {
        if (res.data.success === true) {
            // 提示修改成功
            showMessage('修改成功')
            info.value = false
            getUserPageList()
        } else {
            let message = res.data.message
            console.log(message)
            // 提示消息
            showMessage(message, 'error')
        }
    })
}
// 监听日期组件改变事件，并将开始结束时间设置到变量中
const datepickerChange = (e) => {
  form.startDate = moment(e[0]).format('YYYY-MM-DD HH:mm:ss')
  form.endDate = moment(e[1]).format('YYYY-MM-DD HH:mm:ss')
  console.log('开始时间：' + form.startDate + ', 结束时间：' + form.endDate)
}

const shortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

const pickDate = ref('')

// 表单引用
const searchForm = ref(null)

// 重置查询条件
const reset = () => {
  form.username = ''
  form.startDate = ''
  form.endDate = ''
  pickDate.value = ''
}

// 用户数据
const userList = ref([])
// 当前页码，初值默认为1
const current = ref(1)
// 总记录数，初值默认为0
const total = ref(0)
// 每页显示的记录数，初值默认为10
const size = ref(10)

// 获取分页数据
function getUserPageList() {

  // 调用后台分页接口，并传入所需参数
  findUserPageList({ current: current.value, size: size.value, username: form.username, startDate: form.startDate, endDate: form.endDate, role: form.role })
    .then((res) => {
      if (res.data.success == true) {
        console.log("用户数据" + JSON.stringify(res.data.data))
        userList.value = res.data.data
        current.value = res.data.current
        size.value = res.data.size
        total.value = res.data.total
      }
    })
}
getUserPageList()

// 每页展示数量变更事件
const handleSizeChange = (chooseSize) => {
  size.value = chooseSize
  getTableData()
}

function handleIndex(index) {
  // 假设分页参数为 current（当前页）和 size（每页条数）
  return (current.value - 1) * size.value + index + 1;
}

</script>

<template>
  <!-- 查询表单 -->
  <el-form ref="searchForm" :model="form" style="
        margin:-10px 0 15px -10px;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        gap: 12px 20px;
    " class="card" shadow="always" inline>
    <el-form-item prop="username" style="
            margin: 0;
            display: flex;
            align-items: center;
            gap: 8px;
        ">
      <el-text style="min-width: 60px; margin-right: 15px; text-align: center">用户名称</el-text>
      <el-input v-model="form.username" style="width: 220px" prefix-icon="Search" placeholder="请输入" />
    </el-form-item>

    <el-form-item style="
            margin: 0;
            display: flex;
            align-items: center;
            gap: 8px;">
      <el-text style="min-width: 60px; margin-right: 15px; text-align: center">创建日期</el-text>
      <el-date-picker v-model="pickDate" type="daterange" range-separator="至" start-placeholder="开始时间"
        end-placeholder="结束时间" size="default" :shortcuts="shortcuts" style="width: 360px" @change="datepickerChange" />
    </el-form-item>

    <el-form-item style="margin-left: 10px; justify-content: center; padding-top: 14px">
      <el-button type="primary" plain :icon="Search" style="padding: 8px 20px;">
        查询
      </el-button>
      <el-button type="warning" plain :icon="RefreshRight" style="margin-left: 12px; padding: 8px 20px;" @click="reset">
        重置
      </el-button>
    </el-form-item>
  </el-form>

  <!--数据展示区-->
  <div style="margin:-10px 0 15px -10px" class="card" shadow="always">
    <el-table :data="userList" style="width: 100%" @selection-change="handleSelectionChange" row-key="id">
      <el-table-column type="index" :index="handleIndex" label="序号" width="80px" />
      <el-table-column prop="avatar" label="头像">
        <template #default="scope">
          <el-avatar :src="scope.row.avatar" :icon="UserFilled"
            style="background-color: #8ac8ff; margin-right: 10px;" />
        </template>
      </el-table-column>
      <el-table-column prop="username" label="账号" />
      <el-table-column prop="role" label="角色" />
      <el-table-column prop="createTime" label="创建时间">
        <template #default="scope">
          {{ moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button style="margin-left: 8px" type="primary" plain :icon="Edit" circle @click="selectOneUser(scope.row.id)"></el-button>
          <el-button style="margin-left: 8px" type="danger" plain :icon="Delete" circle></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
      <el-pagination v-model:current-page="current" :page-size="[10, 20, 50]" :size="size" :disabled="disabled"
        background layout="total, prev, pager, next" :total="total" @size-change="handleSizeChange"
        @current-change="getUserPageList" />
    </div>
  </div>

  <!--个人信息对话框-->
  <el-dialog v-model="info" title="个人信息" width="500px" class="custom-dialog">
    <el-form :model="updateForm" label-width="80px" style="padding: 10px;">
      <el-form-item label="用户头像">
        <div style="display: flex; align-items: center;">
          <el-avatar :src="updateForm.avatar" :icon="UserFilled" style="background-color: #8ac8ff; margin-right: 10px;" />
          <el-upload :on-change="handleAvatarChange" :auto-upload="false" :show-file-list="false" :file-list="fileList">
            <el-button size="small" type="primary">修改头像</el-button>
          </el-upload>
        </div>
      </el-form-item>

      <el-form-item label="用户账号">
        <el-input v-model="updateForm.username" autocomplete="off" placeholder="请输入用户名" style="width: 130px" />
      </el-form-item>

      <el-form-item label="用户密码">
                <el-input v-model="updateForm.password" autocomplete="off" placeholder="非必填"
                    style="width: 130px" />
            </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer" style="text-align: right;">
        <el-button @click="info = false">取消</el-button>
        <el-button type="primary" @click="saveInfo">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped></style>